<?php

namespace Icsoc\CustomReportBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Elasticsearch\Client;

/**
 * Class IndexTimeCommand
 * @package Icsoc\CustomReportBundle\Command
 */
class IndexTimeCommand extends ContainerAwareCommand
{
    /**
     * Configures the current command.
     */
    protected function configure()
    {
        $this
            ->setName('report:index:time')
            ->setDescription('将数据库中的时长临时表中的数据导入到Elasticsearch中')
        ;
    }

    /**
     * Executes the current command.
     *
     * This method is not abstract because you can use this class
     * as a concrete class. In this case, instead of defining the
     * execute() method, you set the code to execute by passing
     * a Closure to the setCode() method.
     *
     * @param InputInterface $input An InputInterface instance
     * @param OutputInterface $output An OutputInterface instance
     *
     * @return null|int null or 0 if everything went fine, or an error code
     *
     * @throws \LogicException When this abstract method is not implemented
     *
     * @see setCode()
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        ini_set('memory_limit', '512M');
        $conn = $this->getContainer()->get('doctrine.dbal.default_connection');
        $hosts = $this->getContainer()->getParameter('elasticsearch_hosts');
        $client = new Client(array(
            'hosts' => $hosts,
            'logging' => false
        ));

        $total = $conn->fetchColumn("SELECT COUNT(*) AS total FROM rep_tmp_time");
        $rowPerPage = 10000;
        $pages = ceil($total/$rowPerPage);
        $res = null;

        for ($page = 0; $page < $pages; $page++) {
            $start = $page * $rowPerPage;
            $query = $conn->fetchAll('SELECT * FROM rep_tmp_time LIMIT '.$start.','.$rowPerPage);

            $bulk = array('index' => 'icsoc', 'type' => 'tmp_logs', 'refresh' => true);
            foreach ($query as $key => $row) {
                $bulk['body'][] = array(
                    'index' => array(
                        '_id' => empty($row['id']) ? 0 : 'time' . $row['id']
                    )
                );
                $row['secs'] = $row['endtime'] - $row['starttime'];
                $row['month'] = date('Y-m-01', $row['call_time']);
                $row['day'] = date('Y-m-d', $row['call_time']);
                $row['log_type'] = 'time';

                $bulk['body'][] = $row;
            }
            $client->bulk($bulk);
            unset($bulk);
        }
    }
}
